package com.workcenter.app;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.ppcodes.core.data.DXml;
import com.ppcodes.core.data.DXml.FieldList;
import com.ppcodes.core.utils.UtiDateTime;
import com.ppcodes.core.utils.UtiDialogsFactory;
import com.workcenter.base.UIBase;
import com.workcenter.controls.AdpCstLinearLayout;
import com.workcenter.controls.CstLinearLayout;
import com.workcenter.controls.PopupMenu;
import com.workcenter.entity.NetClient;
import com.workcenter.entity.PubConst;
import com.workcenter.entity.Session;
import com.workcenter.entity.UrlParams;
import com.workcenter.entity.model.ERepairsState;

public class UIDetails extends UIBase
{
   private TextView txtTitle;

   private String RepairsId;
   private TextView txtRepairsId;
   private TextView txtProgress;

   private CstLinearLayout cstRepairs;
   private CstLinearLayout cstWorkorder;
   private CstLinearLayout cstState;

   private ImageView imgAddState;

   // private TextView txtCustomerName;
   // private TextView txtDiagnosis;
   // private TextView txtInstrument;
   // private TextView txtRepairsDate;
   // private TextView txtRepairsPhone;
   // private TextView txtRepairsStaff;
   // private TextView txtInstrumentID;
   // private TextView txtPriority;
   // private TextView txtRoomName;
   // private TextView txtIsStop;

   private void InitControls()
   {
	  cstRepairs = (CstLinearLayout) findViewById(R.id.cstRepairs_details);
	  cstWorkorder = (CstLinearLayout) findViewById(R.id.cstWorkOrder_details);
	  cstState = (CstLinearLayout) findViewById(R.id.cstState_details);

	  txtTitle = (TextView) findViewById(R.id.txtTitle_toptoolbar_details);
	  txtTitle.setText(getString(R.string.title_details));

	  imgAddState = (ImageView) findViewById(R.id.imgAddState_toptoolbar_details);
	  imgAddState.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			View view = getLayoutInflater().inflate(R.layout.dialog_newstate, null);
			final TextView txt = (TextView) view.findViewById(R.id.txtState_newstate);
			txt.setOnClickListener(new View.OnClickListener()
			{
			   @Override
			   public void onClick(View v)
			   {
				  ArrayList<String> list = new ArrayList<String>();
				  if (cstState.getAdapter()==null||!cstState.getAdapter().IsExist("出发"))
				  {
					 list.add("出发");
				  }
				  if (cstState.getAdapter()==null||!cstState.getAdapter().IsExist("到达"))
				  {
					 list.add("到达");
				  }
				  if (cstState.getAdapter()==null||!cstState.getAdapter().IsExist("完成"))
				  {
					 list.add("完成");
				  }
				  if (cstState.getAdapter()==null||!cstState.getAdapter().IsExist("未完成"))
				  {
					 list.add("未完成");
				  }
				  if (cstState.getAdapter()==null||!cstState.getAdapter().IsExist("离开"))
				  {
					 list.add("离开");
				  }
				  if (cstState.getAdapter()==null||!cstState.getAdapter().IsExist("返回"))
				  {
					 list.add("返回");
				  }
				  if (list.size() == 0)
				  {
					 UtiDialogsFactory.getInstance().ShowToastInfoShort(UIDetails.this, "没有可以添加的状态");
				  }
				  else
				  {
					 final PopupMenu menu = new PopupMenu(UIDetails.this, list);
					 menu.setOnItemClickListener(new AdapterView.OnItemClickListener()
					 {
						@Override
						public void onItemClick(AdapterView<?> arg0, View currentView, int position, long arg3)
						{
						   txt.setText(menu.getItem(position));
						   menu.dismiss();
						}
					 });
					 menu.showAsDropDown(txt);
				  }
			   }
			});

			final EditText edt = (EditText) view.findViewById(R.id.edtCommit_newstate);

			Date date=new Date();
			String timeStr=String.format("%s:%s", String.valueOf(date.getHours()),String.valueOf(date.getMinutes()));
			UtiDialogsFactory.getInstance().ShowCustomViewDialogWithOKCancel(UIDetails.this, String.format("新增报修状态(%s)",timeStr), view, new DialogInterface.OnClickListener()
			{
			   @Override
			   public void onClick(DialogInterface dialog, int which)
			   {
				  String type = txt.getText().toString();
				  if (type.equals("请选择"))
				  {
					 UtiDialogsFactory.getInstance().ShowOKAlertDialog(UIDetails.this, getString(R.string.dialog_tips), "请选择一个状态");
				  }
				  else
				  {
					 String opration = null;
					 if (edt.getText().toString().trim().equals(""))
					 {
						opration = "";
					 }
					 else
					 {
						opration = edt.getText().toString().trim();
					 }

					 executeAsyncTask(PubConst.TaskName.AddNewRepairState, new Object[] { type, opration, String.valueOf(txtRepairsId.getTag()) });
					 dialog.dismiss();
				  }
			   }
			});
			// UtiDialogsFactory.getInstance().ShowSingleSelectItemDialog(UIDetails.this,
			// new String[] { "出发", "到达", "完成", "未完成", "离开", "返回" }, 0, new
			// DialogInterface.OnClickListener()
			// {
			// @Override
			// public void onClick(final DialogInterface dialog1, final int
			// which1)
			// {
			// final EditText edt = new EditText(UIDetails.this);
			// UtiDialogsFactory.getInstance().ShowCustomViewDialogWithOKCancel(UIDetails.this,
			// getString(R.string.details_dispose_condition), edt, new
			// DialogInterface.OnClickListener()
			// {
			// @Override
			// public void onClick(DialogInterface dialog2, int which2)
			// {
			// String type = null;
			// switch (which1)
			// {
			// case 0:
			// type = "出发";
			// break;
			// case 1:
			// type = "到达";
			// break;
			// case 2:
			// type = "完成";
			// break;
			// case 3:
			// type = "未完成";
			// break;
			// case 4:
			// type = "离开";
			// break;
			// case 5:
			// type = "返回";
			// break;
			// }
			// String opration = null;
			// if (edt.getText().toString().trim().equals(""))
			// {
			// opration = "";
			// }
			// else
			// {
			// opration = edt.getText().toString().trim();
			// }
			//
			// executeAsyncTask(PubConst.TaskName.AddNewRepairState, new
			// Object[] { type, opration, String.valueOf(txtRepairsId.getTag())
			// });
			// dialog1.dismiss();
			// dialog2.dismiss();
			// }
			// });
			// }
			// });
		 }
	  });

	  RepairsId = getIntent().getStringExtra(PubConst.Intent_Key.REPAIRS_ID);

	  txtRepairsId = (TextView) findViewById(R.id.txtRepairsId_details);
	  txtRepairsId.setText(RepairsId);
	  txtProgress = (TextView) findViewById(R.id.txtProgress_details);
	  txtProgress.setText(getIntent().getStringExtra(PubConst.Intent_Key.PROGRESS));

	  // txtCustomerName = (TextView)
	  // findViewById(R.id.txtCustomerName_details);
	  // txtDiagnosis = (TextView) findViewById(R.id.txtDiagnosis_details);
	  // txtInstrument = (TextView) findViewById(R.id.txtInstrument_details);
	  // txtRepairsDate = (TextView) findViewById(R.id.txtRepairsDate_details);
	  // txtRepairsPhone = (TextView)
	  // findViewById(R.id.txtRepairsPhone_details);
	  // txtRepairsStaff = (TextView)
	  // findViewById(R.id.txtRepairsStaff_details);
	  // txtInstrumentID = (TextView)
	  // findViewById(R.id.txtInstrumentID_details);
	  // txtPriority = (TextView) findViewById(R.id.txtPriority_details);
	  // txtRoomName = (TextView) findViewById(R.id.txtRoomName_details);
	  // txtIsStop = (TextView) findViewById(R.id.txtIsStop_details);
   }

   @Override
   protected void onCreate(Bundle savedInstanceState)
   {
	  super.onCreate(savedInstanceState);
	  setContentView(R.layout.details);
	  InitControls();
	  executeAsyncTask(PubConst.TaskName.LoadRepairsDetails);
   }

   @Override
   public void onAsyncTaskStart(String taskName, Object[] params)
   {
	  try
	  {
		 if (taskName.equals(PubConst.TaskName.LoadRepairsDetails) || taskName.equals(PubConst.TaskName.AddNewRepairState))
		 {
			UtiDialogsFactory.getInstance().ShowLoadingDialogNoTitle(UIDetails.this, getString(R.string.dialog_loading));
			cstRepairs.CleanAllData();
			cstState.CleanAllData();
			cstWorkorder.CleanAllData();
		 }
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UIDetails_onAsyncTaskStart(taskName, params) ", e);
		 }
	  }
   }

   @Override
   public Object onAsyncTaskInBackground(String taskName, Object[] params) throws Exception
   {
	  try
	  {
		 if (taskName != null && taskName.equals(PubConst.TaskName.LoadRepairsDetails))
		 {
			Date time = new Date();
			String monthS = String.valueOf(time.getMonth() + 1);
			String dayS = String.valueOf(time.getDate());
			String todayDate = String.format("%s-%s-%s", String.valueOf(time.getYear() + 1900), monthS.length() == 1 ? ("0" + monthS) : monthS, dayS.length() == 1 ? ("0" + dayS) : dayS);

			return NetClient.GetRepairsDetails(RepairsId, todayDate);
		 }
		 if (taskName != null && taskName.equals(PubConst.TaskName.AddNewRepairState))
		 {
			return NetClient.InsertNewRepairsState(new ERepairsState(String.valueOf(params[0]), String.valueOf(params[1])), String.valueOf(params[2]));
		 }
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UIDetails_onAsyncTaskInBackground(taskName, params) ", e);
		 }
	  }
	  return null;
   }

   @Override
   public void onAsyncTaskEnd(String taskId, String taskName, Object[] params, Object result)
   {
	  try
	  {
		 UtiDialogsFactory.getInstance().DismissLoadingDialog();

		 if (result != null)
		 {
			DXml data = (DXml) result;
			if (data.getHead().GetFieldValue("RspCode").equals(UrlParams.SuccessCode))
			{
			   if (taskName.equals(PubConst.TaskName.LoadRepairsDetails))
			   {
				  // 报修信息===================================================================
				  List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
				  Map<String, Object> map = null;
				  if (data.getBody().GetFieldValue("CustomerName") != null && !data.getBody().GetFieldValue("CustomerName").equals(""))
				  {
					 map = new HashMap<String, Object>();
					 map.put("title", getString(R.string.details_customername2));
					 map.put("name", data.getBody().GetFieldValue("CustomerName"));
					 list.add(map);
				  }
				  if (data.getBody().GetFieldValue("Diagnosis") != null && !data.getBody().GetFieldValue("Diagnosis").equals(""))
				  {
					 map = new HashMap<String, Object>();
					 map.put("title", getString(R.string.details_diagnosis2));
					 map.put("name", data.getBody().GetFieldValue("Diagnosis"));
					 list.add(map);
				  }
				  if (data.getBody().GetFieldValue("Instrument") != null && !data.getBody().GetFieldValue("Instrument").equals(""))
				  {
					 map = new HashMap<String, Object>();
					 map.put("title", getString(R.string.details_instrument2));
					 map.put("name", data.getBody().GetFieldValue("Instrument"));
					 list.add(map);
				  }
				  if (data.getBody().GetFieldValue("InstrumentID") != null && !data.getBody().GetFieldValue("InstrumentID").equals(""))
				  {
					 map = new HashMap<String, Object>();
					 map.put("title", getString(R.string.details_instrumentid2));
					 map.put("name", data.getBody().GetFieldValue("InstrumentID"));
					 list.add(map);
				  }
				  if (data.getBody().GetFieldValue("IsStop") != null && !data.getBody().GetFieldValue("IsStop").equals(""))
				  {
					 map = new HashMap<String, Object>();
					 map.put("title", getString(R.string.details_isstop2));
					 map.put("name", data.getBody().GetFieldValue("IsStop"));
					 list.add(map);
				  }
				  if (data.getBody().GetFieldValue("Priority") != null && !data.getBody().GetFieldValue("Priority").equals(""))
				  {
					 map = new HashMap<String, Object>();
					 map.put("title", getString(R.string.details_priority2));
					 map.put("name", data.getBody().GetFieldValue("Priority"));
					 list.add(map);
				  }
				  if (data.getBody().GetFieldValue("RepairsDate") != null && !data.getBody().GetFieldValue("RepairsDate").equals(""))
				  {
					 map = new HashMap<String, Object>();
					 map.put("title", getString(R.string.details_repairsdate2));
					 map.put("name", data.getBody().GetFieldValue("RepairsDate"));
					 list.add(map);
				  }
				  if (data.getBody().GetFieldValue("RepairsPhone") != null && !data.getBody().GetFieldValue("RepairsPhone").equals(""))
				  {
					 map = new HashMap<String, Object>();
					 map.put("title", getString(R.string.details_repairsphone2));
					 map.put("name", data.getBody().GetFieldValue("RepairsPhone"));
					 list.add(map);
				  }
				  if (data.getBody().GetFieldValue("RepairsStaff") != null && !data.getBody().GetFieldValue("RepairsStaff").equals(""))
				  {
					 map = new HashMap<String, Object>();
					 map.put("title", getString(R.string.details_repairsstaff2));
					 map.put("name", data.getBody().GetFieldValue("RepairsStaff"));
					 list.add(map);
				  }
				  if (data.getBody().GetFieldValue("RoomName") != null && !data.getBody().GetFieldValue("RoomName").equals(""))
				  {
					 map = new HashMap<String, Object>();
					 map.put("title", getString(R.string.details_roomname2));
					 map.put("name", data.getBody().GetFieldValue("RoomName"));
					 list.add(map);
				  }
				  AdpCstLinearLayout cAdapter = new AdpCstLinearLayout(UIDetails.this, list, R.layout.details_item, new String[] { "title", "name" }, new int[] { R.id.txtTitle_details_item,
						R.id.txtName_details_item });
				  cstRepairs.setAdapter(cAdapter);
				  // 派工信息====================================================================
				  List<Map<String, Object>> listW = new ArrayList<Map<String, Object>>();
				  Map<String, Object> mapW = null;
				  if (data.getBody().GetFieldValue("WorkOrderId") != null && !data.getBody().GetFieldValue("WorkOrderId").equals(""))
				  {
					 txtRepairsId.setTag(data.getBody().GetFieldValue("WorkOrderId"));
					 mapW = new HashMap<String, Object>();
					 mapW.put("title", getString(R.string.details_workorderid2));
					 mapW.put("name", data.getBody().GetFieldValue("WorkOrderId"));
					 listW.add(mapW);
				  }
				  if (data.getBody().GetFieldValue("WorkOrderStaff") != null && !data.getBody().GetFieldValue("WorkOrderStaff").equals(""))
				  {
					 mapW = new HashMap<String, Object>();
					 mapW.put("title", getString(R.string.details_workorderstaff2));
					 mapW.put("name", data.getBody().GetFieldValue("WorkOrderStaff"));
					 listW.add(mapW);
				  }
				  if (data.getBody().GetFieldValue("WorkOrderType") != null && !data.getBody().GetFieldValue("WorkOrderType").equals(""))
				  {
					 mapW = new HashMap<String, Object>();
					 mapW.put("title", getString(R.string.details_workordertype2));
					 mapW.put("name", data.getBody().GetFieldValue("WorkOrderType"));
					 listW.add(mapW);
				  }
				  if (data.getBody().GetFieldValue("ServiceType") != null && !data.getBody().GetFieldValue("ServiceType").equals(""))
				  {
					 mapW = new HashMap<String, Object>();
					 mapW.put("title", getString(R.string.details_servicetype2));
					 mapW.put("name", data.getBody().GetFieldValue("ServiceType"));
					 listW.add(mapW);
				  }
				  if (data.getBody().GetFieldValue("Assistant") != null && !data.getBody().GetFieldValue("Assistant").equals(""))
				  {
					 mapW = new HashMap<String, Object>();
					 mapW.put("title", getString(R.string.details_assistant2));
					 mapW.put("name", data.getBody().GetFieldValue("Assistant"));
					 listW.add(mapW);
				  }
				  if (data.getBody().GetFieldValue("Remarks") != null && !data.getBody().GetFieldValue("Remarks").equals(""))
				  {
					 mapW = new HashMap<String, Object>();
					 mapW.put("title", getString(R.string.details_remarks2));
					 mapW.put("name", data.getBody().GetFieldValue("Remarks"));
					 listW.add(mapW);
				  }
				  AdpCstLinearLayout wAdapter = new AdpCstLinearLayout(UIDetails.this, listW, R.layout.details_item, new String[] { "title", "name" }, new int[] { R.id.txtTitle_details_item,
						R.id.txtName_details_item });
				  cstWorkorder.setAdapter(wAdapter);

				  // 报修状态=================================================================================
				  List<Map<String, Object>> listS = new ArrayList<Map<String, Object>>();
				  Map<String, Object> mapS = null;
				  int size = data.getBody().GetFieldList("RepairsStateList").getChilds().length;
				  for (int i = 0; i < size; i++)
				  {
					 FieldList fieldList = data.getBody().GetFieldList("RepairsStateList").GetFieldList(i);
					 mapS = new HashMap<String, Object>();
					 mapS.put("condition", fieldList.GetFieldValue("DisposeCondition"));
					 mapS.put("date", String.format("%s %s", fieldList.GetFieldValue("OperatingDate"), fieldList.GetFieldValue("OperatingTime")));
					 mapS.put("type", fieldList.GetFieldValue("OperatingType"));
					 listS.add(mapS);
				  }

				  AdpCstLinearLayout sAdapter = new AdpCstLinearLayout(UIDetails.this, listS, R.layout.details_state_item, new String[] { "condition", "date", "type" }, new int[] {
						R.id.txtRemarks_details_state_item, R.id.txtDate_details_state_item, R.id.txtType_details_state_item });
				  cstState.setAdapter(sAdapter);

				  // txtCustomerName.setText(data.getBody().GetFieldValue("CustomerName"));
				  // txtDiagnosis.setText(data.getBody().GetFieldValue("Diagnosis"));
				  // txtInstrument.setText(data.getBody().GetFieldValue("Instrument"));
				  // txtInstrumentID.setText(data.getBody().GetFieldValue("InstrumentID"));
				  // txtIsStop.setText(data.getBody().GetFieldValue("IsStop"));
				  // txtPriority.setText(data.getBody().GetFieldValue("Priority"));
				  // txtRepairsDate.setText(data.getBody().GetFieldValue("RepairsDate"));
				  // txtRepairsPhone.setText(data.getBody().GetFieldValue("RepairsPhone"));
				  // txtRepairsStaff.setText(data.getBody().GetFieldValue("RepairsStaff"));
				  // txtRoomName.setText(data.getBody().GetFieldValue("RoomName"));
			   }

			   if (taskName.equals(PubConst.TaskName.AddNewRepairState))
			   {
				  UtiDialogsFactory.getInstance().ShowOKAlertDialog(UIDetails.this, getString(R.string.dialog_tips), getString(R.string.dialog_uploading_success),
						new DialogInterface.OnClickListener()
						{
						   @Override
						   public void onClick(DialogInterface dialog, int which)
						   {
							  executeAsyncTask(PubConst.TaskName.LoadRepairsDetails);
						   }
						});
			   }
			}
			else
			{
			   UtiDialogsFactory.getInstance().ShowToastInfoShort(UIDetails.this, data.getHead().GetFieldValue("RspMsg"));
			}
		 }
		 else
		 {
			UtiDialogsFactory.getInstance().ShowToastInfoShort(UIDetails.this, getString(R.string.dialog_server_failed));
		 }
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UIDetails_onAsyncTaskEnd(taskId, taskName, params, result) ", e);
		 }
	  }
   }
}
